package com.ny.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MqttDeviceClient {
    private static final Logger logger = Logger.getLogger(MqttDeviceClient.class.getName());
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // MQTT连接参数（根据实际环境修改）
    private static final String USERNAME = "new_iot060_iot01";
    private static final String PASSWORD = "b5b47fdb894771d5cd85e8f5cb9890d03a58a375dec93cde738bdeb2a3780beb";
    private static final String CLIENT_ID = "new_iot060_iot01_0_0_2025112515";
    private static final String HOSTNAME = "429388de10.st1.iotda-device.cn-south-1.myhuaweicloud.com";
    private static final int PORT = 8883;
    private static final String BROKER = "ssl://" + HOSTNAME + ":" + PORT;
    public static void main(String[] args) {
        System.out.println("开始初始化MQTT设备客户端...");
        System.out.println("配置参数: Broker=" + BROKER + ", ClientID=" + CLIENT_ID);
        try {
            // 配置SSL（信任所有证书）
            System.out.println("配置SSL上下文...");
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                @Override
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            }}, null);
            System.out.println("SSL上下文配置完成");
            // 创建MQTT客户端
            System.out.println("创建MQTT客户端实例...");
            MqttClient client = new MqttClient(BROKER, CLIENT_ID, new MemoryPersistence());
            // 设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.err.println("MQTT连接丢失: " + cause.getMessage());
                    cause.printStackTrace();
                }
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("收到消息 - Topic: " + topic + ", Message: " + new String(message.getPayload()));
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 消息发送完成，不输出日志以减少干扰
                }
            });
            MqttConnectOptions options = new MqttConnectOptions();
            System.out.println("配置连接选项...");
            // 设置连接参数
            options.setUserName(USERNAME);
            options.setPassword(PASSWORD.toCharArray());
            options.setSocketFactory(sslContext.getSocketFactory());
            options.setCleanSession(true);
            options.setConnectionTimeout(30);
            options.setKeepAliveInterval(60);
            System.out.println("用户名: " + USERNAME);
            System.out.println("连接超时: 30秒");
            System.out.println("心跳间隔: 60秒");
            // 连接华为云IoT平台
            System.out.println("尝试连接到华为云IoT平台...");
            client.connect(options);
            System.out.println("✅ 设备已成功连接到华为云！连接建立时间: " + dateFormat.format(new Date()));
            // 每隔5秒发送模拟数据
            System.out.println("启动定时任务，每5秒发送一次模拟数据...");
            Timer timer = new Timer("DataSenderTimer");
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    try {
                        float temp  = (float) (Math.random() * 100);
                        float humi   = (float) (Math.random() * 100);
                        // 华为云数据格式Math.random() * 100
                        String payload = String.format(
                                "{\"services\":[{\"service_id\":\"new_iot060\",\"properties\":{\"temp\":%.2f,\"humi\":%.2f}}]}",
                                temp, humi
                        );
                        MqttMessage message = new MqttMessage(payload.getBytes("UTF-8"));
                        message.setQos(1);
                        String topic = "$oc/devices/" + CLIENT_ID.split("_")[1] + "/sys/properties/report";
                        client.publish(topic, message);
                        System.out.println("📤 数据发送成功 - 温度: " + String.format("%.2f", temp) + "°C, 湿度: " + String.format("%.2f", humi) + "%");
                    } catch (Exception e) {
                        System.err.println("❌ 发送数据失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }, 0, 5000);
            // 添加关闭钩子以优雅地断开连接
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    System.out.println("正在关闭MQTT客户端...");
                    if (client.isConnected()) {
                        client.disconnect();
                        System.out.println("MQTT客户端已断开连接");
                    }
                    client.close();
                    System.out.println("MQTT客户端已关闭");
                } catch (MqttException e) {
                    System.err.println("关闭MQTT客户端时出错: " + e.getMessage());
                    e.printStackTrace();
                }
            }));
        } catch (MqttException e) {
            System.err.println("❌ MQTT连接失败！错误码: " + e.getReasonCode() + ", 错误信息: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("❌ 程序异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}